package com.qfedu.openplateform.gateway.filter;

import com.alibaba.fastjson.JSON;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.qfedu.openplateform.common.constans.ExceptionDict;
import com.qfedu.openplateform.common.entity.BaseResultBean;
import com.qfedu.openplateform.gateway.utils.Md5Util;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

/**
 *  签名过滤器
 * @author lileijian
 * @create 2021-12-05 0:48
 */
public class SignFilter implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String sign = request.getParameter("sign");
        if (!StringUtils.isEmpty(sign)){
            Map<String, String[]> map = request.getParameterMap();
            // signMap 获取所有的请求参数处理 sign
            Map<String,String>  signMap = new HashMap<>();
            for (String key:map.keySet()) {
                if (!key.equals("sign")) {
                    signMap.put(key, request.getParameter(key));
                }
            }
            String serverSign = Md5Util.md5Signature(signMap, "meiyoumima");

            System.out.println("serverSign = " + serverSign);
            System.out.println("sign = " + sign);
            if (sign.equals(serverSign)){// 签名正确放行
                return true;
            }
        }


        response.setContentType("application/json;charset=utf-8");
        BaseResultBean bean = new BaseResultBean();
        bean.setCode(ExceptionDict.SYSTEMPARAM_SIGN_ERROR);
        bean.setMsg("重新登录");//请求检查签名

        try {
            response.getWriter().println(JSON.toJSONString(bean));
        } catch (JsonProcessingException ex) {
            ex.printStackTrace();
        }

        return false;
    }
}
